﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Collections.Generic;

namespace MultipleTasks
{
    public partial class SPTaskActivity : SequenceActivity
    {
        public SPTaskActivity()
        {
            InitializeComponent();
        }

        public bool IsParallelTask { get; set; }
        public Guid SPTaskId = default(System.Guid);
        public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties SPTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public string TaskTitle { get; set; }
        public string TaskDescription { get; set; }
        public string TaskAssignedTo { get; set; }
        public DateTime TaskDueDate { get; set; }
        private bool complete;
        public string CurrentApprovalLevel = default(string);
        public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties SPAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties SPBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public Guid TaskStatusFieldId = new Guid("c15b34c3-ce7d-490a-b133-3f4de8801b76");

        private string workflowName
            {
            get
            {
                if (this.SPTaskProperties != null)
                {
                    return string.Format("{0}", this.SPTaskProperties.ExtendedProperties["Wfname"]);
                }
                return string.Empty;
            }
        }
        
        private void createSPTask_MethodInvoking(object sender, EventArgs e)
        {

            //Create Task
            SPTaskId = Guid.NewGuid();
            SPTaskProperties.Title = " Task created " + TaskTitle ;
            SPTaskProperties.Description = " Task created " + TaskTitle + this.SPTaskId.ToString();
            SPTaskProperties.AssignedTo = TaskAssignedTo;
            SPTaskProperties.PercentComplete = 0;
            SPTaskProperties.StartDate = DateTime.Today;
            SPTaskProperties.DueDate = TaskDueDate;
            SPTaskProperties.TaskType = 1;
            CurrentApprovalLevel = SPTaskProperties.ExtendedProperties["ApprovalLevel"].ToString();

        }

        private void notComplete(object sender, ConditionalEventArgs e)
        {
            e.Result = !complete;
        }

        string taskStatus = default(string);
        private void onSPTaskChanged_Invoked(object sender, ExternalDataEventArgs e)
        {
             taskStatus = string.Empty;
            if (SPAfterProperties.ExtendedProperties.ContainsKey("ApprovalStatus"))
            {
                if (SPAfterProperties.ExtendedProperties["ApprovalStatus"].ToString().Contains("Accept"))
                    taskStatus = "Completed";
                else if (SPAfterProperties.ExtendedProperties["ApprovalStatus"].ToString().Contains("Reject"))
                    taskStatus = "Reject";
                else
                    taskStatus = SPAfterProperties.ExtendedProperties["ApprovalStatus"].ToString();
            }
            else
                taskStatus = SPAfterProperties.ExtendedProperties[TaskStatusFieldId].ToString();

            if (taskStatus.Equals("ReAssigened", StringComparison.CurrentCultureIgnoreCase))
            {
                if (SPAfterProperties.ExtendedProperties.ContainsKey("DueDate"))
                {
                    string localDefault = "en-GB";
                    if (SPAfterProperties.ExtendedProperties.ContainsKey("DefaultLocal"))
                    {
                        localDefault = SPAfterProperties.ExtendedProperties["DefaultLocal"].ToString();
                    }
                    IFormatProvider culture = new System.Globalization.CultureInfo(localDefault, true);
                    DateTime dt2 = DateTime.Parse
                        (
                        SPAfterProperties.ExtendedProperties["DueDate"].ToString(),
                        culture,
                        System.Globalization.DateTimeStyles.AssumeLocal
                        );

                    this.TaskDueDate = dt2;
                }
                if (SPAfterProperties.ExtendedProperties.ContainsKey("AssignedTo"))
                {
                    this.TaskAssignedTo = SPAfterProperties.ExtendedProperties["AssignedTo"].ToString();
                }
            }

            Dictionary<string, string> Dict = new Dictionary<string, string>();
            SPUtility.ListActivity activity = new SPUtility.ListActivity();
            Dict.Add("Title", this.SPTaskProperties.Title);
            Dict.Add("TaskOutCome", taskStatus);
            Dict.Add("ShortDescription", this.TaskTitle + " (" + this.SPTaskProperties.ExtendedProperties["Itemid"].ToString() + ") " + (IsParallelTask ? " Parallel" : "Serial"));
            Dict.Add("WFTaskInstanceConfigID", this.SPTaskProperties.ExtendedProperties["Itemid"].ToString());
            Dict.Add("ApprovalLevel", CurrentApprovalLevel);
            //activity.AddItem(this.SPTaskProperties.ExtendedProperties["Url"].ToString(), "TaskHandler", Dict);

            if (taskStatus.Equals("Completed") || taskStatus.Equals("Reject") || taskStatus.Equals("SystemComplete"))
                complete = true;

            if (taskStatus.Equals("Reject"))
            {
                SPUtility.WorkflowHelper wfHlp = new SPUtility.WorkflowHelper();

                wfHlp.RjectWFProcess(
                    this.SPTaskProperties.ExtendedProperties["Url"].ToString(),
                    this.SPTaskProperties.ExtendedProperties["List"].ToString(),
                    "ChildID",
                    this.SPTaskProperties.ExtendedProperties["Itemid"].ToString(),
                    workflowName, this.CurrentApprovalLevel);
            }
            else if (complete && !IsParallelTask)
            {
                SPUtility.WorkflowHelper wfHlp = new SPUtility.WorkflowHelper();
                wfHlp.ApproveWFProcess(
                                        this.SPTaskProperties.ExtendedProperties["Url"].ToString(),
                                        this.SPTaskProperties.ExtendedProperties["List"].ToString(),
                                        "ChildID",
                                        this.SPTaskProperties.ExtendedProperties["Itemid"].ToString(),
                                        workflowName,
                                        this.CurrentApprovalLevel, SPTaskId
                                        );
            }
        }

        private void completeSPTask_MethodInvoking(object sender, EventArgs e)
        {
            SPTaskOutcome = taskStatus;// "Task Completed";
        }

        public String SPTaskOutcome = default(System.String);
    }
}
